package jm.data.structure.leet_code;


import java.util.Stack;

/**
 * @Description https://leetcode-cn.com/problems/valid-parentheses/
 * @date 2022/4/7 14:56
 */
public class _20有效的括号 {
    public static void main(String[] args) {

        System.out.println(isValid("()"));
    }

    public static boolean isValid(String s) {
        if (s == null || s.length() % 2 != 0 || s.length() == 0) {
            return false;
        }
        int len = s.length();
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (c == '(' || c== '[' || c == '{' ){
                stack.push(c);
            }else {
                if (stack.isEmpty()) {
                    return false;
                }
                char left = stack.pop();
                if (left == '{' && c!= '}'){
                    return false;
                }
                if (left == '[' && c!= ']'){
                    return false;
                }
                if (left == '(' && c!= ')'){
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}
